﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TaDMS.Models;
using TaDMS.Commons;

namespace TaDMS.Controllers   
{
    [Authorize]
    public class ApiTaskController : ApiController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetAll(int start, int limit)
        {
            int? total;
            var tasks = _unitOfWork.Task.GetData(out total, orderBy: o => o.OrderBy(v => v.CreateDate), isPaging: true, start: start, limit: limit);

            if (String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                var enumerable = tasks as IList<Task> ?? tasks.ToList();
                if (enumerable.Any() && total > 0)
                {
                    var result = new
                    {
                        total = total,
                        success = true,
                        data = enumerable
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Tasks is empty");
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, new HttpError(_unitOfWork.Task.ErrorMessage));
            }
        }

        [System.Web.Http.HttpGet]
        [Authorize(Roles = "Admin, TruongPhong, PhoPhong, ToTruong")]
        public HttpResponseMessage AssignTask(int start, int limit)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            int? total;
            var tasks = _unitOfWork.Task.GetData(out total, orderBy: o => o.OrderBy(v => v.CreateDate), filter: v => v.CreateBy == currentUserId, isPaging: true, start: start, limit: limit, includeProperties: "Employee,TaskEmployees");

            if (String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                if (total > 0)
                {
                    var result = new
                    {
                        total = total,
                        success = true,
                        message = "success",
                        data = tasks.ToList()
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = true,
                    message = "Employees is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.Task.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetTask(int start, int limit)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            int? total;
            var taskIds = _unitOfWork.TaskEmployeeRepository.GetData(out total, orderBy: o => o.OrderBy(v => v.TaskId), filter: v => v.EmployeeId == currentUserId).Select(v => v.TaskId);
            if (taskIds.Any())
            {
                var tasks = _unitOfWork.TaskRepository.GetData(out total, orderBy: o => o.OrderBy(v => v.CreateDate), filter: v => taskIds.Contains(v.TaskId), isPaging: true, start: start, limit: limit, includeProperties: "Employee,TaskEmployees");

                if (String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
                {
                    if (total > 0)
                    {
                        var result = new
                        {
                            total = total,
                            success = true,
                            message = "success",
                            data = tasks.ToList()
                        };
                        return Request.CreateResponse(HttpStatusCode.OK, result);
                    }

                    var empty = new
                    {
                        success = true,
                        message = "Employees is empty"
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, empty);
                }
                else
                {
                    var error = new
                    {
                        success = false,
                        message = _unitOfWork.Task.ErrorMessage
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, error);
                }
            }
            else
            {
                var empty = new
                {
                    success = true,
                    message = "Employees is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
        }

        [System.Web.Http.HttpGet]
        [Authorize(Roles = "Admin, TruongPhong, PhoPhong, ToTruong")]
        public HttpResponseMessage GetComboData(int start, int limit, int all, string query)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            int? total;
            var results = String.IsNullOrEmpty(query) || query.Trim().ToUpper().Equals("ALL")
                              ? _unitOfWork.Task.GetComboData(out total, start, limit, (int)currentUserId, all)
                              : _unitOfWork.Task.GetComboData(out total, start, limit, (int)currentUserId, all).Where(
                                  p =>
                                  p.FirstName.ToUpper().Contains(query.Trim().ToUpper()) ||
                                  p.LastName.ToUpper().Contains(query.Trim().ToUpper())).Distinct();

            if (String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                var enumerable = results as IList<sp_Task_GetResource_Result> ?? results.ToList();
                if (enumerable.Any() && total > 0)
                {
                    var result = new
                    {
                        total = total,
                        success = true,
                        message = "success",
                        data = enumerable
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = false,
                    message = "Employees is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.Task.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpPost]
        [Authorize(Roles = "Admin, TruongPhong, PhoPhong, ToTruong")]
        public HttpResponseMessage Create(Task entity)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            entity.CreateBy = (int)currentUserId;
            entity.CreateDate = DateTime.Now;
            entity.Status = "I";
            var result = _unitOfWork.Task.Create(entity);

            if (result != null && String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                var success = new
                {
                    data = result,
                    success = true,
                    message = "Created"
                };
                return Request.CreateResponse(HttpStatusCode.OK, success);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Craete false: " + _unitOfWork.Task.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }
        
        [System.Web.Http.HttpPost]
        [Authorize(Roles = "Admin, TruongPhong, PhoPhong, ToTruong")]
        public HttpResponseMessage Update(Task entity, string fields)
        {
            var result = _unitOfWork.Task.Update(entity, fields);
            
            if (result != null && String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                var success = new
                {
                    success = true,
                    message = "Created",
                    data = "Thành công"
                };
                return Request.CreateResponse(HttpStatusCode.OK, success);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.Task.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpPost]
        [Authorize(Roles = "Admin, TruongPhong, PhoPhong, ToTruong")]
        public HttpResponseMessage Delete(Task entity)
        {
            var result = _unitOfWork.Task.Delete(entity);

            if (result != null && String.IsNullOrEmpty(_unitOfWork.Task.ErrorMessage))
            {
                var success = new
                {
                    data = result,
                    success = true,
                    message = "Deleted"
                };
                return Request.CreateResponse(HttpStatusCode.OK, success);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Delete false: " + _unitOfWork.Task.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }
    }
}
